<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Cellphonezone
 * @package     Cellphonezone_Cpaypal
 * @copyright   Copyright (c) 2010 Cellphonezone
 * @author $Id$
 */
 
/**
 * Order payment information
 */
class Cellphonezone_Cpaypal_Model_Order_Payment extends Mage_Sales_Model_Order_Payment
{
   
    /**
     * Decide whether authorization transaction may close (if the amount to capture will cover entire order)
     * @param float $amountToCapture
     * @return bool
     */
    protected function _isCaptureFinal($amountToCapture)
    {
		if(!$this->_isAllowCurrency($this->getOrder()))
		{
			return parent::_isCaptureFinal($amountToCapture);
		}
		else
		{
			$orderGrandTotal =  $this->getOrder()->getGrandTotal();
			if (abs($orderGrandTotal - ($this->getAmountPaid() + $amountToCapture)) < 0.01 ) {
				if (false !== $this->getShouldCloseParentTransaction()) {
					$this->setShouldCloseParentTransaction(true);
				}
				return true;
			}
			return false;
		}        
    }

	protected function _isAllowCurrency($order)
    {
    	$currenciesArr = explode(',',Mage::getStoreConfig('paypal/account/allow_currencies',$order->getStore()));
    	if(in_array($order->getOrderCurrencyCode(), $currenciesArr))
    	{
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    }

	/**
     * Process a capture notification from a payment gateway for specified amount
     * Creates an invoice automatically if the amount covers the order base grand total completely
     * Updates transactions hierarchy, if required
     * Prevents transaction double processing
     * Updates payment totals, updates order status and adds proper comments
     *
     * TODO: eliminate logic duplication with capture()
     *
     * @param float $amount
     * @return Mage_Sales_Model_Order_Payment
     */
    public function registerCaptureNotification($amount)
    {
        $this->_generateTransactionId(Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE,
            $this->getAuthorizationTransaction()
        );

        $order   = $this->getOrder();
        $amount  = (float)$amount;
        $invoice = $this->_getInvoiceForTransactionId($this->getTransactionId());

        // register new capture
        if (!$invoice) {
            if ($this->_isCaptureFinal($amount)) {
                $invoice = $order->prepareInvoice()->register();
                $order->addRelatedObject($invoice);
                $this->setCreatedInvoice($invoice);
            } else {
                $this->setIsFraudDetected(true);
                $this->_updateTotals(array('base_amount_paid_online' => $amount));
            }
        }

        $status = true;
        if ($this->getIsTransactionPending()) {
            $message = Mage::helper('sales')->__('Capturing amount of %s is pending approval on gateway.', $this->_formatPrice($amount));
            $state = Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW;
            if ($this->getIsFraudDetected()) {
            	//slash by gold in 2011-08-18 
                //$message = Mage::helper('sales')->__('Order is suspended as its capture amount %s is suspected to be fraudulent.', $this->_formatPrice($amount));
                //$status = Mage_Sales_Model_Order::STATUS_FRAUD;
            }
        } else {
            $message = Mage::helper('sales')->__('Registered notification about captured amount of %s.', $this->_formatPrice($amount));
            $state = Mage_Sales_Model_Order::STATE_PROCESSING;
            if ($this->getIsFraudDetected()) {
            	//slash by gold in 2011-08-18 
                //$state = Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW;
                //$message = Mage::helper('sales')->__('Order is suspended as its capture amount %s is suspected to be fraudulent.', $this->_formatPrice($amount));
                //$status = Mage_Sales_Model_Order::STATUS_FRAUD;
            }
            // register capture for an existing invoice
            if ($invoice && Mage_Sales_Model_Order_Invoice::STATE_OPEN == $invoice->getState()) {
                $invoice->pay();
                $this->_updateTotals(array('base_amount_paid_online' => $amount));
                $order->addRelatedObject($invoice);
            }
        }

        $transaction = $this->_addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE, $invoice, true);
        $message = $this->_prependMessage($message);
        $message = $this->_appendTransactionToMessage($transaction, $message);
        $order->setState($state, $status, $message);
        return $this;
    }
    
	/**
     * Format price with currency sign
     * @param float $amount
     * @return string
     */
    protected function _formatPrice($amount)
    {
    	if ($this->_isAllowCurrency($this->getOrder()))
    	{
    		return $this->getOrder()->getOrderCurrency()->formatTxt($amount);
    	} 
    	else
    	{
    		return parent::_formatPrice($amount);
    	}       
    }
}
